package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.service.TestService;


import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
public class TestServiceImpl implements TestService {

    @Autowired
    @Qualifier("redis")
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;




    public void testLock() {
           //获取锁
        RLock lock = redissonClient.getLock("lock");
        lock.lock(3, TimeUnit.SECONDS);
            try {
            Integer num = (Integer)redisTemplate.opsForValue().get("num");
            if(num!=null){
                num++;
                redisTemplate.opsForValue().set("num",num);
            }
        } finally {
            lock.unlock();
        }


    }


    public String readLock() {
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("readWriteLock");
        RLock readLock = readWriteLock.readLock();
        readLock.lock(10,TimeUnit.SECONDS);
        String msg = (String)redisTemplate.opsForValue().get("msg");

        return msg;
    }

    @Override
    public String writeLock() {
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("readWriteLock");
        RLock rLock = readWriteLock.writeLock();
        rLock.lock(10,TimeUnit.SECONDS);
        redisTemplate.opsForValue().set("msg", UUID.randomUUID().toString());



        return "成功写入内容";
    }
}
